package cn.edu.sgu.www.mhxysy.service.achievement.impl;

import cn.edu.sgu.www.mhxysy.pager.Pager;
import cn.edu.sgu.www.mhxysy.consts.CustomMessages;
import cn.edu.sgu.www.mhxysy.dto.achievement.ChengweiDTO;
import cn.edu.sgu.www.mhxysy.entity.achievement.Chengwei;
import cn.edu.sgu.www.mhxysy.mapper.achievement.ChengweiMapper;
import cn.edu.sgu.www.mhxysy.service.achievement.ChengweiService;
import cn.edu.sgu.www.mhxysy.util.ObjectUtils;
import cn.edu.sgu.www.mhxysy.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class ChengweiServiceImpl implements ChengweiService {

	private final ChengweiMapper chengweiMapper;

	@Autowired
	public ChengweiServiceImpl(ChengweiMapper chengweiMapper) {
		this.chengweiMapper = chengweiMapper;
	}

	@Override
	public void insert(ChengweiDTO chengweiDTO) {
		Chengwei chengwei = toEntity(chengweiDTO);

		chengwei.setId(null);

		chengweiMapper.insert(chengwei);
	}

	@Override
	public void deleteByIds(List<String> ids) {
		chengweiMapper.deleteBatchIds(ids);
	}

	@Override
	public void updateById(ChengweiDTO chengweiDTO) {
		ObjectUtils.requireNonNull(chengweiDTO.getId(), CustomMessages.ID_NOT_NULL);

		Chengwei chengwei = toEntity(chengweiDTO);

		chengweiMapper.updateById(chengwei);
	}

	@Override
	public List<Chengwei> selectAll() {
		return chengweiMapper.selectList(null);
	}

	@Override
	public Chengwei selectById(Integer id) {
		return chengweiMapper.selectById(id);
	}

	@Override
	public List<Chengwei> selectByRoleId(String roleId) {
		// 参数为空，直接返回空集
		if (StringUtils.isNullOrEmpty(roleId)) {
			return new ArrayList<>();
		}

		QueryWrapper<Chengwei> queryWrapper = new QueryWrapper<>();

		queryWrapper.inSql("id",
				"select chengwei_id from role_chengwei where role_id = " + roleId);
		queryWrapper.orderByAsc("chengwei_id");

		return chengweiMapper.selectByRoleId(roleId);
	}

	@Override
	public Page<Chengwei> selectByPage(Pager<Chengwei> pager) {
		QueryWrapper<Chengwei> queryWrapper = Pager.getQueryWrapper(pager, false);
		Page<Chengwei> page = Pager.ofPage(pager);

		return chengweiMapper.selectPage(page, queryWrapper);
	}

	private Chengwei toEntity(ChengweiDTO chengweiDTO) {
		Chengwei chengwei = new Chengwei();

		chengwei.setId(chengweiDTO.getId());
		chengwei.setName(chengweiDTO.getName());
		chengwei.setGet(chengweiDTO.getGet());
		chengwei.setType(chengweiDTO.getType());
		chengwei.setNote(chengweiDTO.getNote());
		chengwei.setPermanent(chengweiDTO.getPermanent());

		return chengwei;
	}

}